package com.hejing.Java比较器;

import org.junit.Test;

import java.util.Arrays;
import java.util.Comparator;

/**
 * ClassName: ComparatorTest
 * Package: com.hejing.Java比较器.Comparator
 * Description:
 *  定制排序
 * @Author: HeJing
 * @Create: 2023-04-17 21:57
 * @Version: 1.0
 */
public class ComparatorTest {

    @Test
    public void test01(){
        Product[] arr = new Product[5];
        arr[0] = new Product("HuaweiMate50pro", 8999);
        arr[1] = new Product("xiaomi13pro", 4999);
        arr[2] = new Product("IPhone12Pro", 8999);
        arr[3] = new Product("VIVoX90", 5999);
        arr[4] = new Product("oppoA99", 3999);

        // 创建一个实现了Comparator 接口的实现类的对象
        Comparator comparator = new Comparator() {

            // 如果判断两个对象o1, o2的大小，其标准就是compare方法方法体需要编写的逻辑
            // 按照价格从高到低排序
            @Override
            public int compare(Object o1, Object o2) {
                if (o1 instanceof  Product && o2 instanceof Product) {
                    Product p1 = (Product) o1;
                    Product p2 = (Product) o2;

                    return -Double.compare(p1.getPrice(), p2.getPrice());
                }
                throw new RuntimeException("类型不匹配");
            }
        };

        // 排序规则: 按照name从高到低
        Comparator comparator1 = new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                if (o1 instanceof Product && o2 instanceof Product) {
                    Product p1 = (Product) o1;
                    Product p2 = (Product) o2;

                    return -p1.getName().compareTo(p2.getName());
                }
                throw new RuntimeException("类型不匹配");
            }
        };

        Arrays.sort(arr, comparator1);

        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }

    }
}





























